<?php

// Remove unnecessary actions and filters
function remove_emoji_support()
{
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('admin_print_styles', 'print_emoji_styles');
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_action('embed_head', 'print_emoji_detection_script');
    remove_filter('the_content_feed', 'wp_staticize_emoji');
    remove_filter('comment_text_rss', 'wp_staticize_emoji');
    remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
    remove_action('wp_head', 'wp_resource_hints', 2);
}
add_action('init', 'remove_emoji_support');

// // 根据页面路径切换主题
add_filter('stylesheet', 'custom_theme_switcher');
add_filter('template', 'custom_theme_switcher');
function custom_theme_switcher($theme) {

    $host=$_SERVER['HTTP_HOST'];
    if(isset($_SERVER['HTTP_X_FORWARDED_HOST']) && !empty($_SERVER['HTTP_X_FORWARDED_HOST'])){
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    }

    $host = explode(".", $host);
    if(count($host) == 3) array_shift($host);

    return getThemeName(implode(".", $host));
}

// Optimize output buffering
add_action('template_redirect', function () {
    ob_start(function ($buffer) {
        $theme_name = wp_get_theme();

        $buffer = preg_replace_callback('/<a[^>]*>/i', function ($matches) {
            $tag = $matches[0];
            //判断是否包含字符串data-no
            if (strpos($tag, 'data-no') !== false) {
                return $tag;
            }
            $tag = preg_replace('/href=(["\'])https?:\/\/[^\/]+(\/[^"\']*)\1/i', 'href=$1$2$1', $tag);
            return $tag;
        }, $buffer);

        // Add Google Analytics script
        $analytics_script = "<script async src='https://www.googletagmanager.com/gtag/js?id=G-MNSRGQNDBF'></script>
        <script>window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'G-MNSRGQNDBF');</script>";
        $buffer = str_replace('</html>', $analytics_script . '</html>', $buffer);

        if (in_array($theme_name, ['girdtemp', 'hihi2'])) {
            return $buffer;
        }

        // Extract and combine inline scripts and styles
        $scripts = extract_inline_content($buffer, 'script');
        $styles = extract_inline_content($buffer, 'style');

        $combined_content = '<script>document.addEventListener("DOMContentLoaded", function () {' . $scripts . '});</script>';
        $combined_content .= '<style>' . $styles . '</style>';
        $buffer = str_replace('</html>', $combined_content . '</html>', $buffer);

        // Add common assets
        if (stripos($buffer, '</head>') !== false) {
            $common_assets = '<script>const themePath = "' . get_template_directory_uri() . '";</script>';
            $common_assets .= '<script type="text/javascript" src="' . get_template_directory_uri() . '/../blocks/comm.js"></script>';
            $common_assets .= '<link rel="stylesheet" href="' . get_template_directory_uri() . '/../blocks/comm.css">';
            $common_assets .= '<link rel="stylesheet" href="' . get_template_directory_uri() . '/style.css">';
            $common_assets .= '<link rel="shortcut icon" href="' . get_template_directory_uri() . '/../static/img/favicon.png" />';
            $buffer = str_replace('</head>', $common_assets . '</head>', $buffer);
        }

        //判断是否是首页
        if (is_front_page()) {
            $buffer = str_replace("<main>", "<main><section id='ballnew' style='padding:var(--gap);'><a href='https://egyball1.com/' data-no><img src='/wp-content/themes/blocks/imgs/banner_egyball1.gif' style='cursor: pointer;' alt='banner' loading='lazy'></a></section>", $buffer);
            $buffer = str_replace("</body>", '<script type="text/javascript" src="' . STATIC_PATH . '/comm.js"></script>' . "</body>", $buffer);
        }
        return $buffer;
    });
});


// Helper function to extract inline content
function extract_inline_content(&$buffer, $tag)
{
    preg_match_all("/<" . $tag . "[^>]*>(.*?)<\/" . $tag . ">/is", $buffer, $matches);
    $content = !empty($matches[1]) ? implode("\n", array_unique($matches[1])) : '';
    $buffer = preg_replace("/<" . $tag . "[^>]*>.*?<\/" . $tag . ">/is", '', $buffer);
    return $content;
}


// Cache-related functions
function get_cache_file_path($cache_key)
{
    $cache_dir = get_template_directory() . '/cache/';
    if (!file_exists($cache_dir)) {
        wp_mkdir_p($cache_dir);
    }
    return $cache_dir . md5($cache_key) . '.txt';
}

function set_file_cache($cache_key, $data, $expire = 0)
{
    $file_path = get_cache_file_path($cache_key);
    $cache_data = ['expire' => $expire > 0 ? time() + $expire : 0, 'data' => $data];
    return file_put_contents($file_path, serialize($cache_data), LOCK_EX) !== false;
}

function get_file_cache($cache_key)
{
    $file_path = get_cache_file_path($cache_key);
    if (!file_exists($file_path)) return false;

    $cache_data = unserialize(file_get_contents($file_path));
    if ($cache_data['expire'] > 0 && time() > $cache_data['expire']) {
        delete_file_cache($cache_key);
        return false;
    }
    return $cache_data['data'];
}

function delete_file_cache($cache_key)
{
    $file_path = get_cache_file_path($cache_key);
    return file_exists($file_path) ? unlink($file_path) : true;
}

function clear_all_file_cache()
{
    $cache_dir = get_template_directory() . '/cache/';
    if (file_exists($cache_dir)) {
        foreach (glob($cache_dir . '*.txt') as $file) {
            if (is_file($file)) unlink($file);
        }
    }
}

function get_post_ids_by_tags($tags, $limit = -1, $order = 'DESC')
{
    $args = [
        'post_type'      => 'post',           // 文章类型
        'post_status'    => 'publish',        // 只获取已发布文章
        'fields'         => 'ids',            // 仅返回文章ID
        'tax_query'      => [
            [
                'taxonomy' => 'post_tag',     // 分类法为标签
                'field'    => is_numeric($tags[0]) ? 'term_id' : 'slug',
                'terms'    => $tags,          // 标签名称或ID
            ],
        ],
        'posts_per_page' => $limit,           // 限制数量
        'orderby'        => 'date',           // 按日期排序
        'order'          => $order,           // 排序方式
        'no_found_rows'  => true,             // 禁用分页计数以提升性能
    ];

    $query = new WP_Query($args);
    return $query->posts; // 直接返回ID数组
}
function get_random_posts($number = 1, $args = [])
{
    if ($number <= 0) return [];

    global $wp_redis;
    $cache_key = 'random_posts_ids_cache';
    $exists = $wp_redis->exists($cache_key);

    if ($exists === 0) {
        $all_post_ids = (new WP_Query(array_merge($args, [
            'fields' => 'ids',
            'posts_per_page' => 1000,
            'post_status' => 'publish',
            'no_found_rows' => true,
            'orderby' => 'ID',
            'order' => 'DESC'
        ])))->posts;
        foreach ($all_post_ids as $post_id) {
            $wp_redis->sadd($cache_key, $post_id);
        }
        $wp_redis->expire($cache_key, 3600);
    }
    $all_post_ids = $wp_redis->srandmember($cache_key, $number);

    if (empty($all_post_ids)) return [];
    $number = max(1, min(30, $number));
    $selected_ids = $number >= count($all_post_ids) ? $all_post_ids : array_intersect_key($all_post_ids, array_flip(array_rand($all_post_ids, $number)));

    $posts = [];
    foreach ($selected_ids as $id) {
        $temp = formatPost($id);
        $temp && $posts[] = $temp;
    }
    return $posts;

    return fetch_posts_by_ids($selected_ids, $number);
}


// Fetch random posts
function get_random_posts1($number = 1, $args = [])
{
    if ($number <= 0) return [];

    $cache_key = 'random_posts_ids_cache';
    $all_post_ids = get_file_cache($cache_key);
    if ($all_post_ids === false) {
        $all_post_ids = (new WP_Query(array_merge($args, [
            'fields' => 'ids',
            'posts_per_page' => 1000,
            'post_status' => 'publish',
            'no_found_rows' => true,
            'orderby' => 'ID',
            'order' => 'DESC'
        ])))->posts;
        set_file_cache($cache_key, $all_post_ids, 3600);
    }

    if (empty($all_post_ids)) return [];
    $number = max(1, min(30, $number));
    $selected_ids = $number >= count($all_post_ids) ? $all_post_ids : array_intersect_key($all_post_ids, array_flip(array_rand($all_post_ids, $number)));

    $posts = [];
    foreach ($selected_ids as $id) {
        $temp = formatPost($id);
        $temp && $posts[] = $temp;
    }
    return $posts;

    return fetch_posts_by_ids($selected_ids, $number);
}

// Fetch posts by category
function get_latest_posts_by_category($category_id = "", $paged = 0, $pageSize = 10)
{
    $paged = $paged ?: (get_query_var('paged') ?: 1);
    $category_id = $category_id ?: get_queried_object_id();

    return get_paginated_category_posts($category_id, $paged, $pageSize);

    $query = new WP_Query([
        'cat' => $category_id,
        'posts_per_page' => $pageSize,
        'paged' => $paged,
        'orderby' => 'date',
        'order' => 'DESC'
    ]);
    return build_post_response($query, $paged);
}

// Fetch posts by keyword
function get_posts_by_keyword($keyword, $paged = 0, $pageSize = 10)
{
    if (empty($keyword)) return [];

    $paged = $paged ?: (get_query_var('paged') ?: 1);
    $query = new WP_Query([
        's' => $keyword,
        'posts_per_page' => $pageSize,
        'paged' => $paged,
        'orderby' => 'date',
        'order' => 'DESC'
    ]);

    return build_post_response($query, $paged);
}

// Helper functions for posts
function fetch_posts_by_ids($ids, $number)
{
    $query = new WP_Query([
        'post__in' => $ids,
        'posts_per_page' => $number,
        'post_status' => 'publish',
        'orderby' => 'post__in'
    ]);

    $posts = [];
    while ($query->have_posts()) {
        $query->the_post();
        $posts[] = [
            'title' => get_the_title(),
            'link' => get_permalink(),
            'date' => get_the_date("Y-m-d H:i:s"),
            'thumbnail' => get_post_thumbnail_or_default(),
            'excerpt' => get_the_excerpt()
        ];
    }
    wp_reset_postdata();

    return $posts;
}

function build_post_response($query, $paged = 1)
{

    $posts = [];
    while ($query->have_posts()) {
        $query->the_post();
        $posts[] = [
            'title' => get_the_title(),
            'link' => get_permalink(),
            'date' => get_the_date("Y-m-d H:i:s"),
            'thumbnail' => get_post_thumbnail_or_default(),
            'excerpt' => get_the_excerpt()
        ];
    }
    wp_reset_postdata();


    return [
        'posts' => $posts,
        'pagination' => [
            'total_pages' => $query->max_num_pages,
            'current_page' => $paged
        ]
    ];
}

function getThumb($content)
{
    preg_match('/<img[^>]+src="([^">]+)"/i', $content, $matches);
    return $matches[1] ?? get_template_directory_uri() . '/images/default-thumbnail.jpg';
}

function get_post_thumbnail_or_default()
{
    if (has_post_thumbnail()) {
        return get_the_post_thumbnail_url(get_the_ID(), 'full');
    }

    $content = get_the_content();
    preg_match('/<img[^>]+src="([^">]+)"/i', $content, $matches);
    return $matches[1] ?? get_template_directory_uri() . '/images/default-thumbnail.jpg';
}

function get_category_post_count($category_id)
{
    global $wp_redis;

    $cache_key = "cat_posts:{$category_id}:total";
    $total = $wp_redis->get($cache_key);
    if (!$total) {
        $query = new WP_Query([
            'cat' => $category_id,
            'posts_per_page' => 1,
            'fields' => 'ids',
            'no_found_rows' => false // 确保返回总数
        ]);

        $total = $query->found_posts;
        $wp_redis->set($cache_key, $total, 3600); // 缓存1小时
    }

    return (int)$total;
}

function get_paginated_category_posts($category_id, $page = 1, $per_page = 10)
{
    global $wp_redis;
    if ($page <= 0 || $per_page <= 0) return [];

    $per_page = max(1, min(50, $per_page));
    $offsetStart = ($page - 1) * $per_page;
    $offsetEnd = $offsetStart + $per_page - 1;

    $batchId = ceil($offsetEnd / 1000);
    $batchs[] = [
        'id' => $batchId,
        'num' => $per_page
    ];

    $overNum = $offsetEnd % 1000;
    if ($overNum < $per_page && $page > 1) {
        $batchs = [
            [
                'id' => $batchId,
                'num' => $overNum
            ],
            [
                'id' => $batchId - 1,
                'num' => $per_page - $overNum
            ]
        ];
    }

    $totalCount = get_category_post_count($category_id);
    $totalPages = ceil($totalCount / $per_page);
    $rs = [
        "pagination" => [
            "total_pages" => $totalPages,
            "current_page" => $page
        ],
        "posts" => []
    ];
    if ($page > $totalPages) return $rs;

    foreach ($batchs as $item) {
        if ($wp_redis->exists("cat_posts:{$category_id}:{$item['id']}") !== 1) {
            setCatBatchCache($category_id, $item['id']);
        }
    }

    if (count($batchs) == 1) {
        $postIds = $wp_redis->list_page("cat_posts:{$category_id}:{$batchId}", $page % intval(1000 / $per_page), $per_page);
    } else {
        $postIds = $wp_redis->lrange("cat_posts:{$category_id}:{$batchs[0]['id']}", 0, $batchs[0]['num'] - 1);
        $postIds = array_merge($postIds, $wp_redis->lrange("cat_posts:{$category_id}:{$batchs[1]['id']}", $batchs[1]['num'] * -1, -1));
    }

    foreach ($postIds as $postId) {
        $temp = formatPost($postId);
        $temp && $rs['posts'][] = $temp;
    }

    return $rs;
}
/**
 * 格式化文章数据
 * 
 * 从Redis缓存获取文章数据，若不存在则从数据库获取并缓存
 * 
 * @param int $postId 文章ID
 * @param array $fields 需要获取的字段数组(可选)
 * @return array 格式化后的文章数据数组，包含id、title、content等字段
 *               - 若文章不存在或未发布，返回空数组
 *               - 若指定了$fields参数，只返回指定字段
 */
function formatPost($postId, array $fields = [])
{
    global $wp_redis;
    if (!$postId) return [];


    $post = $wp_redis->getHash("post:{$postId}", $fields);
    if (empty($post)) {
        $post = get_post($postId);
        if (!$post || $post->post_status != 'publish') return [];

        $rs = [
            'id' => $post->ID,
            'title' => $post->post_title,
            'content' => $post->post_content,
            'excerpt' => $post->post_excerpt ?: wp_trim_words($post->post_content, 55),
            'date' => get_the_date('Y-m-d H:i:s', $post),
            'thumbnail' =>  getThumb($post->post_content),
            'link' => get_permalink($post),
            //不要用匿名函数
            // 'author' => function() use ($post) {
            //     return [
            //         'id' => $post->post_author,
            //         'name' => get_the_author_meta('display_name', $post->post_author),
            //         'avatar' => get_avatar_url($post->post_author)
            //     ];
            // },
            // 'categories' => function() use ($post) {
            //     $terms = get_the_terms($post, 'category');
            //     return $terms ? array_map(function($term) {
            //         return [
            //             'id' => $term->term_id,
            //             'name' => $term->name,
            //             'slug' => $term->slug
            //         ];
            //     }, $terms) : [];
            // },
            // 'tags' => function() use ($post) {
            //     $terms = get_the_terms($post, 'post_tag');
            //     return $terms ? array_map(function($term) {
            //         return [
            //             'id' => $term->term_id,
            //             'name' => $term->name,
            //             'slug' => $term->slug
            //         ];
            //     }, $terms) : [];
            // }
        ];
        $wp_redis->setHash("post:{$post->ID}", $rs);
        $post = $rs;
    }
    // 添加 Redis 缓存逻辑
    $cache_key = "post_tags:{$post['id']}";
    // 尝试从 Redis 缓存中获取标签数据
    $cached_tags = $wp_redis->get($cache_key);
    if ($cached_tags) {
        $post['tags'] = json_decode($cached_tags, true); // 使用 json_decode 解码
    } else {
        //获取标签
        $post['tags'] = get_the_terms($post['id'], 'post_tag');
        if ($post['tags']) {
            $post['tags'] = array_map(function ($term) {
                return [
                    'id' => $term->term_id,
                    'name' => $term->name,
                    'slug' => $term->slug
                ];
            }, $post['tags']);

            // 将标签数据存入 Redis 缓存，设置过期时间为 1 小时
            $wp_redis->set($cache_key, json_encode($post['tags']), 3600); // 使用 json_encode 编码
        }
    }
    return $post;
}


function setCatBatchCache($category_id, $batchId)
{
    if (!$category_id  || $batchId <= 0) {
        return false;
    }

    $posts_per_page = 1000;
    $offset = ($batchId - 1) * $posts_per_page;

    // 3. 查询数据库获取文章数据
    $query = new WP_Query([
        'cat'            => $category_id,
        'posts_per_page' => $posts_per_page,
        'offset'         => $offset,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'post_status'    => 'publish'
    ]);

    $batch_data = [];
    while ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();

        $batch_data[$post_id] = [
            'id' => $post_id,
            'title'     => get_the_title(),
            'link' => get_permalink(),
            'date'      => get_the_date('Y-m-d H:i:s'),
            'content' => apply_filters('the_content', get_the_content()),
            'thumbnail' => getThumb(get_the_content()),
            'excerpt'   => wp_trim_words(get_the_excerpt(), 30)
        ];
    }
    wp_reset_postdata();

    if (empty($batch_data)) {
        $batch_data = ['empty_batch' => true];
    }

    global $wp_redis;
    foreach ($batch_data as $post_id => $post) {
        $wp_redis->add_list("cat_posts:{$category_id}:{$batchId}", $post_id);
        $wp_redis->setHash("post:{$post_id}", $post);
    }
    $wp_redis->expire("cat_posts:{$category_id}:{$batchId}", 3600);
    $wp_redis->expire("post:{$post_id}", 3600);


    return true;
}
function getThemeName(string $host)
{
    $urls = [
        "sendezhuangshi.com",
        "qgdkvb.com",
        "yiancp.com",
        "dadiyuanxian.com",
        "qeqoab.com",
        "pqyjuh.com",
        "szngcw.com",
        "md-vdp.com",
        "ntghjz.com",
        "jljwsp.com",
        "qijuwn.com",
        "nfteae.com",
        "pgyeba.com",
        "mingtianb.com",
        "tygqgs.com",
        "bblxcl.com",
        "huacaiw.com",
        "pengjiawangtao.com",
        "ntcxrf.com",
        "ekkosz.com",
        "zzctch.com",
        "jike0550.com",
        "qkmlga.com",
        "tywhyp.com",
        "shengtaiwenming.com",
        "z2vque.com",
        "rgyikw.com",
        "xxomyu.com",
        "zhistx.com",
        "nfumoe.com",
        "yuang-group.com",
        "mitrontv.com",
        "qxzhjy.com",
        "pewcwr.com",
        "whmkwl.com",
        "wxhbzd.com",
        "sdtjgy.com",
        "cjpzsq.com",
        "nlsjas.com",
        "wkuapp.com",
        "nlemkb.com",
        "nmsxpa.com",
        "ydsjzf.com",
        "yinshanstreet.com",
        "886rx.com",
        "ntowds.com",
        "zrzyst.com",
        "ivheh6.com",
        "bj-shh.com",
        "zhuwozhe.com",
        "nonewait.com",
        "qfhnsc.com",
        "sdthxk.com",
        "uhlpzg.com",
        "markedmusic.com",

        //蜘蛛池转过来的50个域名le 
        "uxfys.com",
        "sihqv.com",
        "pzabo.com",
        "lllpd.com",
        "rzbpz.com",
        "fihjl.com",
        "qecbg.com",
        "nacwf.com",
        "aiye49.top",
        "dmhxr.com",
        "fuwdu.com",
        "ljmcr.com",
        "readytogofinetailoredsuits.com",
        "qkefa.com",
        "jsuvr.com",
        "nzcfh.com",
        "sxcylw.com",
        "hahyh.net",
        "hahvv.net",
        "rzhlg.com",
        "fiiff.net",
        "ffmff.net",
        "rttrr.net",
        "goatstrolls.com",
        "nkckf.com",
        "qdfkjx.com",
        "aymd0.top",
        "vcnkz.com",
        "uuvut.net",
        "nkkkf.com",
        "ffafv.net",
        "llbdp.com",
        "qfblz.com",
        "13908888888.com",
        "jiangshengcenmingshigongzuoshi.com",
        "cneqr.com",
        "zmimb.com",
        "pnztm.com",
        "ayqgz.com",
        "pzdpq.com",
        "1gwdl.com",
        "lsvi1.com",
        "jiapeiwang.com",
        "ijafs.com",
        "hankun56.com",
        "mlahf.com",
        "rggqp.com",
        "nlzkc.com",
        "tut0ugh.com",
        "ddaia.net",
    ];

    $themes = [
        'girdtemp',
        'girdtemp1',
        'lr1',
        'lr2',
        'lr3',
        'lr4',
        'nb1',
        'nb2',
        'nb3',
        'nb4',
        'nb5',
        'boss1',
        'boss2',
        'boss3',
        'boss4',
        'boss5',
        'boss6',
        'boss7',
        'boss8',
        'boss9',
        'boss10',
        'boss11',
        'boss12',
        'boss13',
        'boss14',
        'boss15',
        'boss16',
        'boss17',
        'boss18',
        'boss19',
        'boss20',
    ];

    $index = array_search($host, $urls);
    if ($index === false) {
        return $themes[0];
    }


    return $themes[floor($index / 5)] ?? $themes[0];
}
function blockPath($path)
{
    return  '/wp-content/themes/blocks' . $path;
}
